//
//  NetworkTools.swift
//  艾小夕の微小博
//
//  Created by 艾小新 on 15/10/17.
//  Copyright © 2015年 艾小新. All rights reserved.
//

import UIKit
import AFNetworking


class NetworkTools: AFHTTPSessionManager {
    
    // 应用程序信息
    private let clientId = "1366057716"
    private let appSecret = "8b68ce2bc2bb5aa6260a5344de179564"
    /// 回调地址
    let redirectUri = "http://www.baidu.com"
    
    
    // MARK: 网络单例（管理全局网络访问）
    static let sharedTools:NetworkTools  = {
       
        let tools = NetworkTools(baseURL: NSURL(string: "https://api.weibo.com/"))
        tools.responseSerializer.acceptableContentTypes = NSSet(objects: "application/json", "text/json", "text/javascript", "text/plain") as Set<NSObject>
        return tools
        
    }()
    
    
    // MARK: 通过单例拿code
    func oauthURL() -> NSURL {
        
        return NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(clientId)&redirect_uri=\(redirectUri)")!
    }
    
    /// 网络回调类型别名
    typealias HMNetFinishedCallBack = (result: [String: AnyObject]?, error: NSError?)->()
    
    func loadAccessToken(code: String, finished: HMNetFinishedCallBack) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let params = ["client_id": clientId,
            "client_secret": appSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirectUri]
        
        // 测试代码-设置返回的数据格式
        // responseSerializer = AFHTTPResponseSerializer()
        
        POST(urlString, parameters: params, success: { (_, JSON) -> Void in
            // {"access_token":"2.00ml8IrFX6ZhGE09ce0ebf870fPkb1","remind_in":"157679999","expires_in":157679999,"uid":"5365823342"}
            // 没有引号的值在反序列化的时候，会变成 NSNumber
            // print(NSString(data: JSON as! NSData, encoding: NSUTF8StringEncoding))
            
            finished(result: JSON as? [String: AnyObject], error: nil)
            }) { (_, error) -> Void in
                print(error)
                finished(result: nil, error: error)
        }
    }
    
    
    
    
    
    

}
